//
//  BN_NoticeViewCtrlData.m
//  BabyNow
//
//  Created by 刘泽琛 on 14-5-13.
//  Copyright (c) 2014年 iMobile. All rights reserved.
//

#import "BN_NoticeViewCtrlData.h"

@implementation BN_NoticeViewCtrlData {
    NSArray *files_;
    NSInteger replTime_;
    NSIndexPath *currentIndexPath;
}

- (id)init {
    if (self = [super init]) {
        
        if (!self.noticeHelper) {
            self.noticeHelper = [[BN_NoticeHelper alloc]init];
        }
        if (!self.netArray) {
            self.netArray = [[NSMutableArray alloc]init];
        }        
        // 数据请求
        [self loadNetData];
        
        // 通知
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(likeChangeNetArr:) name:K_NOTICE_LIKE_NETARRAY_VALUE object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(shareChangeNetArr:) name:K_NOTICE_SHARE_NETARRAY_VALUE object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(deleChangeNetArr:) name:K_NOTICE_DELE_NETARRAY_VALUE object:nil];
    }
    return self;
}

- (void)noticeRefresh {
    if (!self.noticeHelper) {
        self.noticeHelper = [[BN_NoticeHelper alloc]init];
    }
    [self loadNetData];
}

- (void)toDynamic_NoticeReloadList:(Dynamic_Notice_ReloadList)reloadList {
    self.listReload = reloadList;
}

- (void)tableViewRowForCellReload:(RowForCellReload)rowReload {
    self.rowReload = rowReload;
}

#pragma mark
#pragma mark 列表委托和数据源

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    BN_SchoolNoticeCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    NSInteger height;
    if (indexPath.row != self.netArray.count-1) {
        height = cell.cellHeight;
    }else {
        cell.dividerView.hidden = YES;
        height = cell.cellHeight-20;
    }
    return height;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.netArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    // 配置cell
    static NSString *identifier = @"BN_SchoolNoticeCell";
    BOOL nibsResistered = NO;
    if (!nibsResistered) {
        UINib *nib = [UINib nibWithNibName:NSStringFromClass([BN_SchoolNoticeCell class]) bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:identifier];
        nibsResistered = YES;
    }
    BN_SchoolNoticeCell *cell = (BN_SchoolNoticeCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
    cell.tag = indexPath.row;
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    for (UIView *view in cell.disPlayImageView.subviews) {
        [view removeFromSuperview];
    }
    for (UIView *view in cell.replView.subviews) {
        [view removeFromSuperview];
    }
    cell.titleTextLabel.text = @"";
    cell.contentTextLabel.text = @"";
    
    cell.cellHeight = 0;
    cell.singleRelpHeight = 0;
    cell.relpHeight = 0;

    // 权限
    // NSInteger notiUserType = [self.netArray[indexPath.row][@"notiUserType"] integerValue];
    
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    
    // 是否收藏
    cell.favoFlg = [self.netArray[indexPath.row][@"favoFlg"] integerValue];
    // 通知ID
    cell.notiId = [NSString stringWithFormat:@"%@",self.netArray[indexPath.row][@"notiId"]];
    
    cell.praiFlg = [self.netArray[indexPath.row][@"praiFlg"]intValue];

    NSString *replTimeStr = [NSString stringWithFormat:@"%@",self.netArray[indexPath.row][@"replTime"]];
    cell.replTime = [replTimeStr integerValue];
    
    // 班级或全校图片
    NSInteger classOrSchoolFlg = [self.netArray[indexPath.row][@"notiUserType"] integerValue];
    switch (classOrSchoolFlg) {
        case ENUM_ROLE_LEADER:
            cell.classSchoolImageView.image = [UIImage imageNamed:@"schoolflg"];
            break;
        case ENUM_ROLE_CLASS_TEACHER:
            cell.classSchoolImageView.image = [UIImage imageNamed:@"classflg"];
            break;
        default:
            break;
    }
    
    // 日期
    NSString *dateStr = self.netArray[indexPath.row][@"notiDate"];
    NSRange rang = NSMakeRange(0, 19);
    NSString *strRang = [dateStr substringWithRange:rang];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    NSTimeZone *timeZone = [NSTimeZone localTimeZone];
    [formatter setTimeZone:timeZone];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *dateTime = [formatter dateFromString:strRang];
    cell.createTimeLabel.text = [IMB_TimeFormatModel timeFormat:dateTime];
    
    NSString *replTime = [NSString stringWithFormat:@"%@",self.netArray[indexPath.row][@"replTime"]];
    NSString *praiTime = [NSString stringWithFormat:@"%@",self.netArray[indexPath.row][@"praiTime"]];
    cell.praiTime = praiTime;
    if (![replTime isEqual:[NSNull null]]) {
        for (UILabel *view in cell.pinglunBtn.subviews) {
            if ([view isKindOfClass:[UILabel class]]) {
                [view removeFromSuperview];
            }
        }
        UILabel *pinlunLabel = [[UILabel alloc]init];
        switch (MAIN_VERSION) {

            case 6:
                pinlunLabel.frame = CGRectMake((60-30)/2+17, (31-17)/2+2, 50, 12);
                break;
            default:
                pinlunLabel.frame = CGRectMake((60-30)/2+17, (31-17)/2+1, 50, 12);

                break;
        }
        pinlunLabel.backgroundColor = [UIColor clearColor];
        UIColor *color = APP_OBJECT_GREEN_COLOR;
        pinlunLabel.textColor = color;
        pinlunLabel.font = [UIFont systemFontOfSize:12];
        pinlunLabel.text = replTime;
        [cell.pinglunBtn addSubview:pinlunLabel];
    }
    
    if (![praiTime isEqual:[NSNull null]]) {
        for (UILabel *view in cell.xihuanBtn.subviews) {
            if ([view isKindOfClass:[UILabel class]]) {
                [view removeFromSuperview];
            }
        }
        UILabel *xihuanLabel = [[UILabel alloc]init];
        switch (MAIN_VERSION) {
            case 6:
                xihuanLabel.frame = CGRectMake((60-30)/2+17, (31-17)/2+2, 50, 12);
                break;
            default:
                xihuanLabel.frame = CGRectMake((60-30)/2+17, (31-17)/2+1, 50, 12);
                break;
        }
        xihuanLabel.backgroundColor = [UIColor clearColor];
        UIColor *color = APP_OBJECT_GREEN_COLOR;
        xihuanLabel.textColor = color;
        xihuanLabel.font = [UIFont systemFontOfSize:12];
        xihuanLabel.text = praiTime;
        [cell.xihuanBtn addSubview:xihuanLabel];
    }
    [cell dealLikeBtnColorState];
    
    // 评论数组
    cell.replArr = self.netArray[indexPath.row][@"repls"];
    
    // 文字标题
    NSString *postSubj = self.netArray[indexPath.row][@"notiSubj"];
    if (![postSubj isEqual:[NSNull null]]) {
        cell.titleTextLabel.text = postSubj;
    }else {
        cell.titleTextLabel.text = @"";
    }
    [cell.titleTextLabel sizeToFit];
    
    // 文字内容
    NSString *postCont = self.netArray[indexPath.row][@"notiCont"];
    if (![postCont isEqual:[NSNull null]]) {
        cell.contentTextLabel.text = postCont;
    }else {
        cell.contentTextLabel.text = @"";
    }
    NSArray *files = self.netArray[indexPath.row][@"files"];
    [cell contentTextToGroupView:files];
    [cell.contentTextLabel sizeToFit];
    
    // 是否隐藏底部分割线
    if (indexPath.row == self.netArray.count-1) {
        cell.dividerView.hidden = YES;
    }else {
        cell.dividerView.hidden = NO;
    }
    return cell;
}

#pragma mark 
#pragma mark 网络数据
- (void)loadNetData {
    __weak typeof(self) weakSelf = self;
    self.noticeHelper.queryNoticeListHandler = ^(id result,NSString *errorMsg){
        // update by jason yan 2014-05-30
        if (errorMsg) {
            [LZCHINT title:errorMsg type:LZCError duration:2 places:HINT_PLACES callBack:NULL];
            weakSelf.listReload(YES,weakSelf.isScrollToTop);
        }
        if(result){
            [weakSelf reveiceNetInfo:result];
        }
    };
    [self.noticeHelper refreshNoticeList];
}

- (void)reveiceNetInfo:(id)result {
    self.netArray = (NSMutableArray *)result;
    self.listReload(YES,self.isScrollToTop);
    self.isScrollToTop = NO;
}

#pragma mark - 刷新控件的代理方法
- (void)upLoadFinished:(MJRefreshBaseView *)refreshView {
    // 列表开始加载，开始数据请求
    // [self loadNextNetData];
    
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [refreshView endRefreshing];
}

- (void)doneWithView:(MJRefreshBaseView *)refreshView
{
    // 列表开始刷新，开始数据请求
    [self loadNetData];
    
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [refreshView endRefreshing];
}

- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    switch ([refreshView viewType]) {
        case -1:
            [self performSelector:@selector(doneWithView:) withObject:refreshView afterDelay:0.85];
            break;
        case 1:
            [self performSelector:@selector(upLoadFinished:) withObject:refreshView afterDelay:0];
            break;
        default:
            break;
    }
}

- (void)refreshViewEndRefreshing:(MJRefreshBaseView *)refreshView
{
    // code...
}

- (void)refreshView:(MJRefreshBaseView *)refreshView stateChange:(MJRefreshState)state
{
    switch (state) {
        case MJRefreshStateNormal:
            break;
            
        case MJRefreshStatePulling:
            break;
            
        case MJRefreshStateRefreshing:
            break;
        default:
            break;
    }
}

#pragma mark 通知
- (void)likeChangeNetArr:(NSNotification *)notification {
    // praiFlg
    NSArray *recevieArr = notification.object;
    NSInteger tag = [recevieArr[0] integerValue];
    NSInteger praiFlg = [recevieArr[1] integerValue];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    dict = self.netArray[tag];
    // 点赞标记
    [dict setObject:[NSString stringWithFormat:@"%ld",(long)praiFlg] forKey:@"praiFlg"];
    // 点赞次数
    NSInteger praiTime = [dict[@"praiTime"]integerValue];
    switch (praiFlg) {
        case 0:
            praiTime = praiTime - 1;
            break;
        case 1:
            praiTime = praiTime + 1;
            break;
        default:
            break;
    }
    [dict setObject:[NSString stringWithFormat:@"%ld",(long)praiTime] forKey:@"praiTime"];
    [self.netArray replaceObjectAtIndex:tag withObject:dict];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:tag inSection:0];
    NSArray *indexArray = [NSArray arrayWithObject:indexPath];
    self.rowReload(indexArray,NO);
}

- (void)shareChangeNetArr:(NSNotification *)notification {
    NSInteger tag = [notification.object integerValue];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    dict = self.netArray[tag];
    [dict setObject:@"1" forKey:@"favoFlg"];
    [self.netArray replaceObjectAtIndex:tag withObject:dict];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:tag inSection:0];
    NSArray *indexArray = [NSArray arrayWithObject:indexPath];
    self.rowReload(indexArray,NO);
}

- (void)deleChangeNetArr:(NSNotification *)notification {
    NSInteger tag = [notification.object intValue];
    [self.netArray removeObjectAtIndex:tag];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:tag inSection:0];
    NSArray *indexArray = [NSArray arrayWithObject:indexPath];
    self.rowReload(indexArray,YES);
}

#pragma mark
#pragma mark ScrollView
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [_refreshView scrollViewDidScroll];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [_refreshView scrollViewDidEndDraging];
}

#pragma mark - slimeRefresh delegate
- (void)slimeRefreshStartRefresh:(SRRefreshView *)refreshView
{
    [_refreshView performSelector:@selector(endRefresh)
                     withObject:nil afterDelay:0.5
                        inModes:[NSArray arrayWithObject:NSRunLoopCommonModes]];
}

- (void)slimeRefreshFinishedRefresh:(SRRefreshView*)refreshView {
    NSLog(@"刷新完成");
}

#pragma mark
#pragma mark 生命周期
- (void)dealloc
{
    NSLog(@"通知Modal释放...");
}

@end
